package com.itools.core.controller;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @project: itools-backend
 * @description:
 * @author: XUCHANG
 * @create: 2021-03-29 14:29
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Qualifier("jwtTokenStore")
    @Autowired
    private TokenStore tokenService;

//    @RequestMapping("/getCurrentUser")
//    public Object getCurrentUser(@RequestParam("access_token") String token) {
//        OAuth2Authentication oAuth2Authentication =  tokenService.readAuthentication(token);
//
//        return oAuth2Authentication.getUserAuthentication()/*.getPrincipal()*/;
//    }
    @PreAuthorize("hasAnyAuthority('getCurrentUser')")
//    @RolesAllowed("hasAnyRole('getCurrentUser')")
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication,
                                 HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        String token = null;
        if(header!=null){
            token = header.substring(header.indexOf("bearer") + 7);
        }else {
            token = request.getParameter("access_token");
        }
        return Jwts.parser()
                .setSigningKey("123123".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }
}
